from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

db = SQLAlchemy()

class Team(db.Model):
    __tablename__ = 'teams'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False, unique=True)
    league = db.Column(db.String(100), nullable=False)  # 所属联赛
    game = db.Column(db.String(100), nullable=False)    # 所属游戏
    icon = db.Column(db.String(255), default='default_team.png')  # 战队图标
    total_matches = db.Column(db.Integer, default=0)
    wins = db.Column(db.Integer, default=0)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    @property
    def win_rate(self):
        if self.total_matches == 0:
            return 0
        return round((self.wins / self.total_matches) * 100)

class Match(db.Model):
    __tablename__ = 'matches'
    
    id = db.Column(db.Integer, primary_key=True)
    game_type = db.Column(db.String(50), nullable=True, default='lol')  # 游戏类型，设为可空
    team1_id = db.Column(db.Integer, db.ForeignKey('teams.id'), nullable=False)  # 主队
    team2_id = db.Column(db.Integer, db.ForeignKey('teams.id'), nullable=False)  # 客队
    winner_id = db.Column(db.Integer, db.ForeignKey('teams.id'), nullable=False) # 胜者
    profit = db.Column(db.Float, nullable=False)  # 盈利
    match_date = db.Column(db.DateTime, default=datetime.utcnow)  # 比赛日期
    
    # 新增字段
    investment = db.Column(db.Float, default=0)  # 总投资额
    return_amount = db.Column(db.Float, default=0)  # 总回报额
    match_format = db.Column(db.String(20), default="Bo3")  # 比赛赛制，可以是Bo3或Bo5
    team1_blue_side = db.Column(db.Boolean, default=True)  # 主队是否为蓝色方
    total_games = db.Column(db.Integer, default=3)  # 实际比赛局数
    games_json = db.Column(db.Text, default="{}")  # 每局比赛的详细信息，存储为JSON字符串
    
    team1 = db.relationship('Team', foreign_keys=[team1_id])
    team2 = db.relationship('Team', foreign_keys=[team2_id])
    winner = db.relationship('Team', foreign_keys=[winner_id]) 